<?php

/**
 * Framework_Controller
 *
 * @author Application Support Group
 * @copyright University of Georgia
 * @package BAMF
 * @filesource
 */

class Framework_Controller {

	/**
	 * run
	 *
	 * @access public
	 * @return mixed PEAR_Error on failure, true on success
	 */
	static public function run() {

		$module = "" ;
		$class = "" ;
		$item = null ;
		$config = array() ;

		if( file_exists( CONFIG_INI )) {
			$config = parse_ini_file( CONFIG_INI, true ) ;
		}


		// get the last arg; if numeric, assign value to $item, else assign null
		$args = !empty( $_GET['args'] ) ? $_GET['args'] : array() ;
		$argCount = count( $args ) ;
		$lastArgIndex = $argCount - 1 ;
		$lastArg = ($argCount > 0) ? $args[$lastArgIndex] : null ;

		if( is_numeric( $lastArg )) {
			$item = $lastArg ;
			unset( $args[$lastArgIndex] ) ;
		}

		// $module is the first arg
		$module = !empty( $args[0] ) ? $args[0] : "" ;


		if( !empty( $module ) && is_string( $module )) {

			// get rid of null args: EG. as would result from http://my.example.edu/Index/
			foreach( $args as $key=>$val ) {
				if( !$val ) { 
					unset( $args[$key] ); 
				}
			}

			// assemble the module class and make sure no funny business
			$class = implode( "_", $args ) ;
			if( !preg_match( '/^[A-Z0-9_]+$/i', $class ) && $module != 'favicon.ico') {
				return Framework_ErrorHandler::raiseError( "Invalid module requested. [$class]", __METHOD__."::".__LINE__ ) ;
			}

			$class = "Module_".$class ;

			// Action class 'main' method
			$event = 'doAction';

			if( !class_exists( $class )) {
				if( defined( 'APPLICATION_404_URL' ) && !headers_sent()) {
					header( "Location: " . APPLICATION_404_URL ) ;
				} else {
					if( !headers_sent() ) { 
						header( "HTTP/1.0 404 File Not Found" );
					}
					die( "Error 404: The requested resource cannot be found." ) ;
				}
			}

			$instance = new $class() ;
			if( !Framework_Module::isValid($instance) ) {
				return Framework_ErrorHandler::raiseError("Requested module is not a valid framework module.", __METHOD__."::".__LINE__);
			}

			$instance->itemNumber = $item ;
			$instance->moduleName = $module ;

			$authField = DEFAULT_AUTH_USER_FIELD ;
			if( isset( $config[ 'auth_user_field' ][ $module ] )) {
				$authField = $config[ 'auth_user_field' ][ $module ] ;
			}
			
			if( $instance->authenticated( $authField )) {
				$result = $instance->$event();

				if (!Framework_ErrorHandler::isError($result, __METHOD__."::".__LINE__ )) {
					$presenter = Framework_Presenter_PresenterFactory::build($instance->presenter,$instance);

					// display the output
					if (!Framework_ErrorHandler::isError($presenter, __METHOD__."::".__LINE__ )) {
						$success = $presenter->display();

						//
						// log activity
						//

	// Pear Log documentation indicates that we must use the $var = &Log::singleton() syntax or we'll get a copy, not a reference

						switch( ERROR_HANDLER_MODE ) {
							case DB_ERROR_MODE:
								$conf = array( 'dsn'=> Framework_DB_Utility::unserializeDsn( FRAMEWORK_DSN )) ;
								$conf['identLimit'] = 200  ;
								$logger = &Log::singleton( DB_ERROR_MODE, FRAMEWORK_LOG_TABLE, FRAMEWORK_LOG_IDENT, $conf ) ;
								break ;
							default:
								$logger = &Log::singleton( FILE_ERROR_MODE, FRAMEWORK_LOG_FILE ) ;				
								break ;
						}

						$postData = $_POST ;
						if( !empty( $postData['password'] )) {
							$postData['password'] = "******" ;
						}

						$messageArray = array( 
								'type'=>"ACTIVITY",
								'timestamp'=>date( 'c', FRAMEWORK_TIMESTAMP ), 
								'location'=>get_class( $instance ),
								'sessionid'=> !empty( $_REQUEST[FRAMEWORK_SESSION_NAME] ) ? "{$_REQUEST[FRAMEWORK_SESSION_NAME]}" : "0",
								'data'=>array(
									'get'=>$_GET, 
									'post'=>$postData, 
									'session'=>$_SESSION 
									) 
								);
						$xml = new XML_Serializer();
						$xml->serialize($messageArray) ;
						$aMessage = '<?xml version="1.0" encoding="UTF-8" ?>'."\n" ;
						$aMessage .= $xml->getSerializedData();

						if( !empty( $logger )) {
							$logger->setIdent( !empty($_REQUEST[FRAMEWORK_SESSION_NAME]) ? $_REQUEST[FRAMEWORK_SESSION_NAME] : "Uninitialized session" ) ;
							$logger->log( $aMessage ) ;						
						} else {
							die( __METHOD__." - Could not instantiate Log object." ) ;
						}

						return $success ;

					} else {
						return Framework_ErrorHandler::raiseError($presenter->getMessage(), __METHOD__."::".__LINE__ );
					}
				} else {
					//
					//	(Added 2006.01.04 pbarabe)
					//	perhaps we need some error handling here:	
					//
					return Framework_ErrorHandler::raiseError( $result->getDebugInfo(), __METHOD__."::".__LINE__ ) ;
				}
			} else {
				$_SESSION['destination_uri'] = $_SERVER['REQUEST_URI'] ;
				
				if ( isset( $config['login_path'][$module] ) && !empty( $config['login_path'][$module] )) {
					$go = APPLICATION_BASE_URL.$config['login_path'][$module] ;
				} else {
					$go = DEFAULT_LOGIN_PATH ;
				}
				
				header( "Location: ".$go ) ;

				exit();
			}
		} else {
			header( "Location: ".APPLICATION_BASE_URL."/".FRAMEWORK_DEFAULT_MODULE );
			exit();
		}
	}
}

?>
